package com.ruoyi.order.config;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.jdbc.DataSourceHealthContributorAutoConfiguration;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator;
import org.springframework.boot.jdbc.metadata.DataSourcePoolMetadataProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
import java.util.Map;


/**
 * <p> 引入sharding-jdbc后数据源健康配置 </p>
 *
 * @author zhengqingya
 * @description 解决问题 ConnectionCallback; isValid; nested exception is java.sql.SQLFeatureNotSupportedException: isValid
 * 原因 springboot2.4数据源健康检查
 * @date 2021/10/28 10:54
 */
@Configuration
public class DataSourceHealthConfig extends DataSourceHealthContributorAutoConfiguration{
//    @Value("${spring.datasource.dbcp2.validation-query:select 1}")
//    private String defaultQuery;
//
//    public DataSourceHealthConfig(Map<String, DataSource> dataSources, ObjectProvider<DataSourcePoolMetadataProvider> metadataProviders) {
//        super(dataSources, metadataProviders);
//    }
//
//    @Override
//    protected AbstractHealthIndicator createIndicator(DataSource source) {
//        DataSourceHealthIndicator indicator = (DataSourceHealthIndicator) super.createIndicator(source);
//        if (!StringUtils.hasText(indicator.getQuery())) {
//            indicator.setQuery(defaultQuery);
//        }
//        return indicator;
//    }

    @Value("${spring.datasource.dbcp2.validation-query:select 1}")
    private String defaultQuery;

    public DataSourceHealthConfig(Map<String, DataSource> dataSources, ObjectProvider<DataSourcePoolMetadataProvider> metadataProviders) {
        super(dataSources, metadataProviders);
    }

    @Override
    protected AbstractHealthIndicator createIndicator(DataSource source) {
        DataSourceHealthIndicator indicator = (DataSourceHealthIndicator) super.createIndicator(source);
        if (!StringUtils.hasText(indicator.getQuery())) {
            indicator.setQuery(defaultQuery);
        }
        return indicator;
    }

}
